<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>应急仓库管理系统</title>
  <!-- 引入外部资源 -->
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

  <!-- Tailwind 配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#1E40AF', // 深蓝色主色调
            secondary: '#3B82F6',
            danger: '#EF4444',
            success: '#10B981'
          }
        }
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  </style>
</head>
<body class="bg-gray-50 min-h-screen">
<!-- 顶部导航 -->
<header class="bg-primary text-white shadow-md">
  <div class="container mx-auto px-4 py-4 flex justify-between items-center">
    <div class="flex items-center gap-2">
      <i class="fa fa-warehouse text-2xl"></i>
      <h1 class="text-xl font-bold">应急仓库管理系统</h1>
    </div>
    <div>
      <span class="bg-white/20 px-3 py-1 rounded-full text-sm">管理员</span>
    </div>
  </div>
</header>

<!-- 主要内容区 -->
<main class="container mx-auto px-4 py-8">
  <!-- 页面标题和操作按钮 -->
  <div class="flex flex-col md:flex-row justify-between items-start md:items-center mb-6">
    <div>
      <h2 class="text-2xl font-bold text-gray-800">仓库管理</h2>
      <p class="text-gray-500 mt-1">管理应急仓库的基本信息</p>
    </div>
    <button id="addBtn" class="mt-4 md:mt-0 bg-primary hover:bg-primary/90 text-white px-5 py-2 rounded-lg flex items-center transition-all">
      <i class="fa fa-plus mr-2"></i>新增仓库
    </button>
  </div>

  <!-- 搜索框 -->
  <div class="bg-white p-4 rounded-lg card-shadow mb-6">
    <div class="flex flex-col sm:flex-row gap-3">
      <input type="text" id="searchInput" placeholder="搜索仓库名称、位置..."
             class="flex-1 px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none">
      <button id="searchBtn" class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-all">
        <i class="fa fa-search mr-1"></i>搜索
      </button>
      <button id="resetBtn" class="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition-all">
        重置
      </button>
    </div>
  </div>

  <!-- 仓库列表表格 -->
  <div class="bg-white rounded-lg card-shadow overflow-hidden">
    <table class="w-full">
      <thead>
      <tr class="bg-gray-50 border-b border-gray-200">
        <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">ID</th>
        <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">仓库名称</th>
        <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">位置</th>
        <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">最大容量</th>
        <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">联系人</th>
        <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">联系电话</th>
        <th class="px-6 py-3 text-left text-sm font-semibold text-gray-700">操作</th>
      </tr>
      </thead>
      <tbody id="warehouseTable">
      <!-- 表格内容将通过JS动态生成 -->
      <tr>
        <td colspan="7" class="px-6 py-10 text-center text-gray-500">
          <div class="flex flex-col items-center">
            <i class="fa fa-spinner fa-spin text-primary text-2xl mb-2"></i>
            <span>加载中...</span>
          </div>
        </td>
      </tr>
      </tbody>
    </table>

    <!-- 分页 -->
    <div class="px-6 py-3 border-t border-gray-200 flex justify-between items-center">
      <div class="text-sm text-gray-500">
        共 <span id="totalCount">0</span> 条记录
      </div>
      <div class="flex gap-2">
        <button id="prevPage" class="px-3 py-1 border border-gray-200 rounded hover:bg-gray-50 disabled:opacity-50" disabled>
          上一页
        </button>
        <button id="nextPage" class="px-3 py-1 border border-gray-200 rounded hover:bg-gray-50 disabled:opacity-50" disabled>
          下一页
        </button>
      </div>
    </div>
  </div>
</main>

<!-- 添加/编辑仓库的模态框 -->
<div id="warehouseModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
  <div class="bg-white rounded-lg w-full max-w-md mx-4 transform transition-all duration-300 scale-95 opacity-0" id="modalContent">
    <div class="p-5 border-b border-gray-200 flex justify-between items-center">
      <h3 id="modalTitle" class="text-lg font-bold">添加仓库</h3>
      <button id="closeModal" class="text-gray-400 hover:text-gray-600">
        <i class="fa fa-times text-xl"></i>
      </button>
    </div>
    <form id="warehouseForm" class="p-5 space-y-4">
      <input type="hidden" id="warehouseId"> <!-- 用于编辑时存储ID -->

      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">仓库名称 <span class="text-danger">*</span></label>
        <input type="text" id="name" name="name" required
               class="w-full px-3 py-2 border border-gray-200 rounded focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none">
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">位置 <span class="text-danger">*</span></label>
        <input type="text" id="location" name="location" required
               class="w-full px-3 py-2 border border-gray-200 rounded focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none">
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">最大容量</label>
        <input type="number" id="maxCapacity" name="maxCapacity" min="0"
               class="w-full px-3 py-2 border border-gray-200 rounded focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none">
        <p class="text-xs text-gray-500 mt-1">单位：件/吨</p>
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">联系人 <span class="text-danger">*</span></label>
        <input type="text" id="contactPerson" name="contactPerson" required
               class="w-full px-3 py-2 border border-gray-200 rounded focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none">
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">联系电话 <span class="text-danger">*</span></label>
        <input type="tel" id="phone" name="phone" required
               class="w-full px-3 py-2 border border-gray-200 rounded focus:ring-2 focus:ring-primary/30 focus:border-primary outline-none">
      </div>

      <div class="flex justify-end gap-3 pt-2">
        <button type="button" id="cancelBtn" class="px-4 py-2 border border-gray-200 rounded hover:bg-gray-50">
          取消
        </button>
        <button type="submit" class="px-4 py-2 bg-primary text-white rounded hover:bg-primary/90">
          保存
        </button>
      </div>
    </form>
  </div>
</div>

<!-- 删除确认模态框 -->
<div id="deleteModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 hidden">
  <div class="bg-white rounded-lg w-full max-w-md mx-4 p-5 transform transition-all duration-300 scale-95 opacity-0" id="deleteModalContent">
    <div class="text-center">
      <div class="w-16 h-16 bg-danger/10 rounded-full flex items-center justify-center mx-auto mb-4">
        <i class="fa fa-exclamation-triangle text-danger text-2xl"></i>
      </div>
      <h3 class="text-lg font-bold mb-2">确认删除</h3>
      <p class="text-gray-600 mb-5">确定要删除该仓库吗？此操作不可恢复。</p>
      <input type="hidden" id="deleteId">
      <div class="flex justify-center gap-3">
        <button id="cancelDeleteBtn" class="px-4 py-2 border border-gray-200 rounded hover:bg-gray-50">
          取消
        </button>
        <button id="confirmDeleteBtn" class="px-4 py-2 bg-danger text-white rounded hover:bg-danger/90">
          确认删除
        </button>
      </div>
    </div>
  </div>
</div>

<!-- 提示消息 -->
<div id="toast" class="fixed top-4 right-4 px-4 py-3 rounded-lg shadow-lg flex items-center transform translate-x-full transition-all duration-300 z-50">
  <i id="toastIcon" class="mr-2"></i>
  <span id="toastText"></span>
</div>

<script>
  // 全局变量
  let currentPage = 1;
  const pageSize = 10;
  let totalData = []; // 存储所有数据用于分页

  // DOM元素
  const warehouseTable = document.getElementById('warehouseTable');
  const addBtn = document.getElementById('addBtn');
  const warehouseModal = document.getElementById('warehouseModal');
  const modalContent = document.getElementById('modalContent');
  const modalTitle = document.getElementById('modalTitle');
  const closeModal = document.getElementById('closeModal');
  const cancelBtn = document.getElementById('cancelBtn');
  const warehouseForm = document.getElementById('warehouseForm');
  const warehouseId = document.getElementById('warehouseId');
  const deleteModal = document.getElementById('deleteModal');
  const deleteModalContent = document.getElementById('deleteModalContent');
  const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
  const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
  const deleteId = document.getElementById('deleteId');
  const toast = document.getElementById('toast');
  const toastIcon = document.getElementById('toastIcon');
  const toastText = document.getElementById('toastText');
  const searchInput = document.getElementById('searchInput');
  const searchBtn = document.getElementById('searchBtn');
  const resetBtn = document.getElementById('resetBtn');
  const totalCount = document.getElementById('totalCount');
  const prevPage = document.getElementById('prevPage');
  const nextPage = document.getElementById('nextPage');

  // 页面加载时获取数据
  document.addEventListener('DOMContentLoaded', () => {
    loadWarehouseData();
    bindEvents();
  });

  // 绑定所有事件
  function bindEvents() {
    // 添加按钮
    addBtn.addEventListener('click', () => {
      openModal('add');
    });

    // 模态框关闭按钮
    closeModal.addEventListener('click', closeModalFunc);
    cancelBtn.addEventListener('click', closeModalFunc);

    // 表单提交
    warehouseForm.addEventListener('submit', handleFormSubmit);

    // 删除相关
    cancelDeleteBtn.addEventListener('click', closeDeleteModalFunc);
    confirmDeleteBtn.addEventListener('click', handleDeleteConfirm);

    // 搜索和重置
    searchBtn.addEventListener('click', handleSearch);
    resetBtn.addEventListener('click', handleReset);

    // 分页
    prevPage.addEventListener('click', () => {
      if (currentPage > 1) {
        currentPage--;
        renderTable();
      }
    });

    nextPage.addEventListener('click', () => {
      if (currentPage * pageSize < totalData.length) {
        currentPage++;
        renderTable();
      }
    });
  }

  // 加载仓库数据
  function loadWarehouseData() {
    fetch('/EmergencyWarehouseServlet') // 后端Servlet地址
            .then(response => response.json())
            .then(data => {
              totalData = data;
              currentPage = 1; // 重置页码
              renderTable();
            })
            .catch(error => {
              console.error('加载数据失败:', error);
              showToast('加载失败', 'error');
              warehouseTable.innerHTML = `
                        <tr>
                            <td colspan="7" class="px-6 py-10 text-center text-gray-500">
                                <i class="fa fa-exclamation-circle text-danger mr-2"></i>
                                加载失败，请刷新页面重试
                            </td>
                        </tr>
                    `;
            });
  }

  // 渲染表格数据
  function renderTable() {
    // 更新总数
    totalCount.textContent = totalData.length;

    // 计算分页数据
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, totalData.length);
    const pageData = totalData.slice(startIndex, endIndex);

    // 更新分页按钮状态
    prevPage.disabled = currentPage === 1;
    nextPage.disabled = endIndex >= totalData.length;

    // 清空表格
    warehouseTable.innerHTML = '';

    if (pageData.length === 0) {
      warehouseTable.innerHTML = `
                    <tr>
                        <td colspan="7" class="px-6 py-10 text-center text-gray-500">
                            没有找到数据
                        </td>
                    </tr>
                `;
      return;
    }

    // 生成表格行
    pageData.forEach(warehouse => {
      const tr = document.createElement('tr');
      tr.className = 'border-b border-gray-200 hover:bg-gray-50';
      tr.innerHTML = `
                    <td class="px-6 py-3 text-sm text-gray-600">${warehouse.id}</td>
                    <td class="px-6 py-3 text-sm font-medium">${escapeHtml(warehouse.name)}</td>
                    <td class="px-6 py-3 text-sm text-gray-600">${escapeHtml(warehouse.location)}</td>
                    <td class="px-6 py-3 text-sm text-gray-600">${warehouse.maxCapacity || '-'}</td>
                    <td class="px-6 py-3 text-sm text-gray-600">${escapeHtml(warehouse.contactPerson)}</td>
                    <td class="px-6 py-3 text-sm text-gray-600">${escapeHtml(warehouse.phone)}</td>
                    <td class="px-6 py-3 text-sm">
                        <div class="flex gap-2">
                                                        <button onclick="editWarehouse('${warehouse.id}')"
                                    class="text-primary hover:text-primary/80 transition-colors" title="编辑">
                                <i class="fa fa-pencil"></i>
                            </button>
                            <button onclick="deleteWarehouse('${warehouse.id}')"
                                    class="text-danger hover:text-danger/80 transition-colors" title="删除">
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </td>
                `;
      warehouseTable.appendChild(tr);
    });
  }

  // 打开添加/编辑模态框
  function openModal(type, data = null) {
    if (type === 'add') {
      modalTitle.textContent = '添加仓库';
      warehouseId.value = '';
      warehouseForm.reset();
    } else {
      modalTitle.textContent = '编辑仓库';
      warehouseId.value = data.id;
      document.getElementById('name').value = data.name || '';
      document.getElementById('location').value = data.location || '';
      document.getElementById('maxCapacity').value = data.maxCapacity || '';
      document.getElementById('contactPerson').value = data.contactPerson || '';
      document.getElementById('phone').value = data.phone || '';
    }

    // 显示模态框并添加动画
    warehouseModal.classList.remove('hidden');
    setTimeout(() => {
      modalContent.classList.remove('scale-95', 'opacity-0');
      modalContent.classList.add('scale-100', 'opacity-100');
    }, 10);
  }

  // 编辑仓库
  function editWarehouse(id) {
    fetch(`/EmergencyWarehouseServlet?action=get&id=${id}`)
            .then(response => response.json())
            .then(warehouse => {
              if (warehouse && warehouse.id) {
                openModal('edit', warehouse);
              } else {
                showToast('未找到仓库信息', 'error');
              }
            })
            .catch(error => {
              console.error('编辑失败:', error);
              showToast('获取仓库信息失败', 'error');
            });
  }

  // 删除仓库 - 显示确认框
  function deleteWarehouse(id) {
    deleteId.value = id;
    deleteModal.classList.remove('hidden');
    setTimeout(() => {
      deleteModalContent.classList.remove('scale-95', 'opacity-0');
      deleteModalContent.classList.add('scale-100', 'opacity-100');
    }, 10);
  }

  // 处理表单提交
  function handleFormSubmit(e) {
    e.preventDefault();

    const formData = new FormData();
    formData.append('name', document.getElementById('name').value);
    formData.append('location', document.getElementById('location').value);
    formData.append('maxCapacity', document.getElementById('maxCapacity').value);
    formData.append('contactPerson', document.getElementById('contactPerson').value);
    formData.append('phone', document.getElementById('phone').value);

    const id = warehouseId.value;
    if (id) {
      formData.append('id', id);
      formData.append('action', 'update');
    } else {
      formData.append('action', 'add');
    }

    fetch('/EmergencyWarehouseServlet', {
      method: 'POST',
      body: formData
    })
            .then(response => response.json())
            .then(result => {
              if (result.success) {
                closeModalFunc();
                loadWarehouseData();
                showToast(id ? '更新成功' : '添加成功', 'success');
              } else {
                showToast(result.message || '操作失败', 'error');
              }
            })
            .catch(error => {
              console.error('提交失败:', error);
              showToast('网络错误，请重试', 'error');
            });
  }

  // 处理删除确认
  function handleDeleteConfirm() {
    const id = deleteId.value;
    const formData = new FormData();
    formData.append('action', 'delete');
    formData.append('id', id);

    fetch('/WarehouseManagementServlet', {                                                           
      method: 'POST',
      body: formData
    })
            .then(response => response.json())
            .then(result => {
              if (result.success) {
                closeDeleteModalFunc();
                loadWarehouseData();
                showToast('删除成功', 'success');
              } else {
                showToast(result.message || '删除失败', 'error');
              }
            })
            .catch(error => {
              console.error('删除失败:', error);
              showToast('网络错误，请重试', 'error');
            });
  }

  // 搜索处理
  function handleSearch() {
    const keyword = searchInput.value.trim().toLowerCase();
    if (!keyword) {
      loadWarehouseData();
      return;
    }

    // 前端筛选（也可改为后端筛选）
    const filteredData = totalData.filter(item =>
            item.name.toLowerCase().includes(keyword) ||
            item.location.toLowerCase().includes(keyword) ||
            item.contactPerson.toLowerCase().includes(keyword)
    );

    totalData = filteredData;
    currentPage = 1;
    renderTable();
  }

  // 重置搜索
  function handleReset() {
    searchInput.value = '';
    loadWarehouseData();
  }

  // 关闭模态框
  function closeModalFunc() {
    modalContent.classList.remove('scale-100', 'opacity-100');
    modalContent.classList.add('scale-95', 'opacity-0');
    setTimeout(() => {
      warehouseModal.classList.add('hidden');
    }, 300);
  }

  // 关闭删除模态框
  function closeDeleteModalFunc() {
    deleteModalContent.classList.remove('scale-100', 'opacity-100');
    deleteModalContent.classList.add('scale-95', 'opacity-0');
    setTimeout(() => {
      deleteModal.classList.add('hidden');
    }, 300);
  }

  // 显示提示消息
  function showToast(message, type = 'info') {
    toastText.textContent = message;

    if (type === 'success') {
      toastIcon.className = 'fa fa-check-circle text-success text-xl mr-2';
      toast.className = 'fixed top-4 right-4 px-4 py-3 bg-success/10 text-success rounded-lg shadow-lg flex items-center transform translate-x-full transition-all duration-300 z-50';
    } else {
      toastIcon.className = 'fa fa-exclamation-circle text-danger text-xl mr-2';
      toast.className = 'fixed top-4 right-4 px-4 py-3 bg-danger/10 text-danger rounded-lg shadow-lg flex items-center transform translate-x-full transition-all duration-300 z-50';
    }

    setTimeout(() => toast.classList.replace('translate-x-full', 'translate-x-0'), 10);
    setTimeout(() => toast.classList.replace('translate-x-0', 'translate-x-full'), 3000);
  }

  // HTML转义
  function escapeHtml(unsafe) {
    if (!unsafe) return '';
    return unsafe
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
  }

  // 暴露函数到全局
  window.editWarehouse = editWarehouse;
  window.deleteWarehouse = deleteWarehouse;
</script>
</body>
</html>